package com.tencent.qcloud.qiaoqiao.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.qcloud.qiaoqiao.R;
import com.tencent.qcloud.qiaoqiao.login.TCLoginActivity;
import com.tencent.qcloud.qiaoqiao.login.TCUserMgr;
import com.tencent.qcloud.qiaoqiao.mainui.list.TCVideoInfo;
import com.tencent.qcloud.qiaoqiao.ui.BaseFragment;
import com.tencent.qcloud.qiaoqiao.ui.activity.VideoLoginActivity;
import com.tencent.qcloud.qiaoqiao.ui.activity.WebViewActivity;
import com.tencent.qcloud.qiaoqiao.ui.adapter.CommentListAdapter;
import com.tencent.qcloud.qiaoqiao.ui.bean.CommentListBean;
import com.tencent.qcloud.qiaoqiao.ui.net.FastJsonTools;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpRequest;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpResultListener;
import com.tencent.qcloud.qiaoqiao.ui.tools.Constant;
import com.tencent.qcloud.qiaoqiao.ui.tools.MyAppUtils;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ScreenUtils;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ToastUtils;
import com.tencent.qcloud.qiaoqiao.ui.view.SharePopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.FormBody;
import okhttp3.RequestBody;


public class HomeOperationFragment extends BaseFragment {

    @BindView(R.id.home_share_btn)
    TextView homeShareBtn;
    @BindView(R.id.home_tags_btn)
    TextView homeTagsBtn;
    @BindView(R.id.home_comment_btn)
    TextView homeCommentBtn;
    @BindView(R.id.home_follow_btn)
    ImageView homeFollowBtn;
    @BindView(R.id.home_follow_user_img)
    CircleImageView homeFollowUserImg;
    @BindView(R.id.home_video_name)
    TextView homeVideoName;
    @BindView(R.id.home_video_context)
    TextView homeVideoContext;
    @BindView(R.id.home_buy_btn)
    ImageView homeBuyBtn;

    public static HomeOperationFragment newInstance() {
        HomeOperationFragment fragment = new HomeOperationFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    private List<CommentListBean.ListBean> commentListBean;
    private CommentListBean commentBean;
    public CommentListAdapter commentListAdapter;
    private List<TCVideoInfo> mVideoList;
    TCVideoInfo currentTcLiveInfo;
    int commentIndex = 1;

    /**
     * 评论列表
     */
    private void loadCommentListData() {
        if (currentTcLiveInfo == null) {
            ToastUtils.showShort("数据错误");
            return;
        }
        RequestBody formBody = new FormBody.Builder()
                .add("file_id", currentTcLiveInfo.fileid)
                .add("userid", TCUserMgr.getInstance().getUserId() + "")
                .add("index", commentIndex + "")
                .add("count", Constant.SIZE + "").build();
        HttpRequest.requestPost("comment_list", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                commentIndex++;
                commentBean = FastJsonTools.getPerson(data, CommentListBean.class);
                if (commentListBean != null) {
                    commentListBean.addAll(commentBean.getList());
                    commentListAdapter.setNewData(commentListBean);
                    comment_count_tx.setText(commentBean.getTotal() + "条评论");
                    if (commentListBean.size() >= commentBean.getTotal()) {
                        commentRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }

            @Override
            public void onFailure(String data) {
                ToastUtils.showShort("失败");
            }
        });
    }

    String tempSearch;

    /**
     * 提交评论
     */
    private void submitCommentData() {
        if (currentTcLiveInfo == null) {
            ToastUtils.showShort("数据错误");
            return;
        }
        if (TCUserMgr.getInstance().hasUser()) {
            startActivity(new Intent(mContext, VideoLoginActivity.class));
            return;
        }
        tempSearch = search_edit_view.getText().toString().trim();
        if (TextUtils.isEmpty(tempSearch)) {
            ToastUtils.showShort("请输入要评论的内容");
            return;
        }
        RequestBody formBody = new FormBody.Builder()
                .add("file_id", currentTcLiveInfo.fileid)
                .add("userid", TCUserMgr.getInstance().getUserId() + "")
                .add("to_userid", currentTcLiveInfo.userid + "")
                .add("content", tempSearch)
                .add("add_time", System.currentTimeMillis() + "").build();
        HttpRequest.requestPost("comment", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                commentListBean.clear();
                commentIndex = 1;
                commentListAdapter.setNewData(commentListBean);
                search_edit_view.setText("");
                loadCommentListData();
            }

            @Override
            public void onFailure(String data) {
                ToastUtils.showShort("失败");
            }
        });
    }

    /**
     * 关注
     */
    private void loadInterestData() {
        if (currentTcLiveInfo == null) {
            ToastUtils.showShort("数据错误");
            return;
        }
        if (TCUserMgr.getInstance().hasUser()) {
            startActivity(new Intent(mContext, VideoLoginActivity.class));
            return;
        }
        RequestBody formBody = new FormBody.Builder()
                .add("userid", TCUserMgr.getInstance().getUserId())
                .add("to_userid", currentTcLiveInfo.userid).build();
        HttpRequest.requestPost("interest", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                final int action = jsonObject.getInteger("action");
                if (action == 1) {
                    currentTcLiveInfo.interest_state = 1;
                    ToastUtils.showShort("关注成功");
                    homeFollowBtn.setBackground(ContextCompat.getDrawable(mContext, R.mipmap.home_followed_icon));
                } else {
                    currentTcLiveInfo.interest_state = 0;
                    ToastUtils.showShort("取消关注成功");
                    homeFollowBtn.setBackground(ContextCompat.getDrawable(mContext, R.mipmap.home_follow_icon));
                }
                homeCommentBtn.post(new Runnable() {
                    @Override
                    public void run() {
                        for (TCVideoInfo bean : mVideoList) {
                            if (bean.userid.equals(currentTcLiveInfo.userid)) {
                                bean.interest_state = action;
                            }
                        }
                    }
                });
            }

            @Override
            public void onFailure(String data) {
                ToastUtils.showShort("失败");
            }
        });
    }

    /**
     * 点赞
     */
    private void loadCommendData() {
        if (currentTcLiveInfo == null) {
            ToastUtils.showShort("数据错误");
            return;
        }
        RequestBody formBody = new FormBody.Builder()
                .add("userid", TCUserMgr.getInstance().getUserId())
                .add("file_id", currentTcLiveInfo.fileid).build();
        HttpRequest.requestPost("commend", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                int action = jsonObject.getInteger("action");
                showCommentView(action);
            }

            @Override
            public void onFailure(String data) {
                ToastUtils.showShort("失败");
            }
        });
    }

    private void showCommentView(int action) {
        Drawable drawable = null;
        if (action == 0) {
            ToastUtils.showShort("点赞成功");
            currentTcLiveInfo.commend_state = 1;
            drawable = ContextCompat.getDrawable(mContext, R.mipmap.home_ike_icon);
        } else {
            currentTcLiveInfo.commend_state = 0;
            ToastUtils.showShort("取消点赞成功");
            drawable = ContextCompat.getDrawable(mContext, R.mipmap.home_un_like_icon);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        homeTagsBtn.setCompoundDrawables(null, drawable, null, null);
    }

    private void showCommentView2(int action) {
        Drawable drawable = null;
        if (action == 1) {
            drawable = ContextCompat.getDrawable(getActivity(), R.mipmap.home_ike_icon);
        } else {
            drawable = ContextCompat.getDrawable(getActivity(), R.mipmap.home_un_like_icon);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        homeTagsBtn.setCompoundDrawables(null, drawable, null, null);
    }

    /**
     * 给评论点赞
     */
    private void subComentData(final CommentListBean.ListBean bean) {
        RequestBody formBody = new FormBody.Builder()
                .add("userid", TCUserMgr.getInstance().getUserId())
                .add("comment_id", bean.getComment_id()).build();
        HttpRequest.requestPost("comment_commend", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                int action = jsonObject.getInteger("action");
                if (action == 1) {
                    ToastUtils.showShort("点赞成功");
                    bean.setCommend_count(bean.getCommend_count() + 1);
                    bean.setComment_state(1);
                } else {
                    ToastUtils.showShort("取消点赞");
                    bean.setCommend_count(bean.getCommend_count() - 1);
                    bean.setComment_state(0);
                }
                commentListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String data) {
                ToastUtils.showShort("失败");
            }
        });
    }

    public void showCurrentView(TCVideoInfo currentTcLiveInfo, int commentIndex) {
        this.currentTcLiveInfo = currentTcLiveInfo;
        this.commentIndex = commentIndex;
        showCommentView2(currentTcLiveInfo.commend_state);
        int collect = currentTcLiveInfo.interest_state;
        if (collect == 1) {
            homeFollowBtn.setBackground(ContextCompat.getDrawable(mContext, R.mipmap.home_followed_icon));
        } else {
            homeFollowBtn.setBackground(ContextCompat.getDrawable(mContext, R.mipmap.home_follow_icon));
        }
        Glide.with(HomeOperationFragment.this).load(currentTcLiveInfo.avatar).error(R.mipmap.app_icon).into(homeFollowUserImg);
        homeVideoContext.setText(currentTcLiveInfo.title);
        String name = currentTcLiveInfo.nickname;
        homeVideoName.setText(MyAppUtils.getName(name));
        int goodsidstate = currentTcLiveInfo.goodsidstate;
        if (goodsidstate==1){
            homeBuyBtn.setVisibility(View.VISIBLE);
        } else {
            homeBuyBtn.setVisibility(View.GONE);
        }
    }

    public void shareUI() {
        SharePopupWindow window = new SharePopupWindow(mContext, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }, homeCommentBtn);
        window.setData(currentTcLiveInfo);
    }

    private TextView comment_count_tx;
    private EditText search_edit_view;
    private SmartRefreshLayout commentRefreshLayout = null;

    @SuppressLint("WrongConstant")
    public void commentWindowUI() {
        commentListAdapter = new CommentListAdapter();
        commentListBean = new ArrayList<>();
        commentListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                subComentData(commentListBean.get(position));
            }
        });
        commentListAdapter.addData(commentListBean);
        commentIndex = 1;
        loadCommentListData();
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.window_comment_layout, null);
        //创建并显示popWindow
        int w = ScreenUtils.getScreenWidth();
        final CustomPopWindow commentPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView).size(w, RelativeLayout.LayoutParams.MATCH_PARENT)
                .create();
        commentPopWindow.getPopupWindow().setAnimationStyle(R.style.popwin_anim_style);
        commentPopWindow.showAsDropDown(homeCommentBtn);

//        commentPopWindow.getPopupWindow().setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
//        commentPopWindow.getPopupWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        commentRefreshLayout = (SmartRefreshLayout) contentView.findViewById(R.id.comment_refreshLayout);
        RecyclerView comment_recyclerView = (RecyclerView) contentView.findViewById(R.id.comment_recyclerView);
        comment_recyclerView.setAdapter(commentListAdapter);
        comment_count_tx = (TextView) contentView.findViewById(R.id.comment_count_tx);
        contentView.findViewById(R.id.share_top_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commentPopWindow.dissmiss();
            }
        });

        comment_recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        commentRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                commentRefreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        commentListBean.clear();
                        commentIndex = 1;
                        commentListAdapter.setNewData(commentListBean);
                        loadCommentListData();
                        commentRefreshLayout.finishRefresh();
                        commentRefreshLayout.setNoMoreData(false);
                    }
                });
            }
        });
        commentRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                commentRefreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        loadCommentListData();
                        commentRefreshLayout.finishRefresh();
                        commentRefreshLayout.finishLoadMore();
                    }
                });
            }
        });
        search_edit_view = (EditText) contentView.findViewById(R.id.search_edit_view);
        search_edit_view.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    submitCommentData();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            onPause();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mVideoList = new ArrayList<TCVideoInfo>();

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @OnClick({R.id.home_share_btn, R.id.home_tags_btn, R.id.home_comment_btn, R.id.home_follow_btn,R.id.home_buy_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_share_btn:
                shareUI();
                break;
            case R.id.home_tags_btn:
                loadCommendData();
                // homeTagsBtn.setBackground(ContextCompat.getDrawable(mContext, R.mipmap.home_un_like_icon));
                break;
            case R.id.home_comment_btn:
                commentWindowUI();
                break;
            case R.id.home_follow_btn:
                loadInterestData();
                break;
            case R.id.home_buy_btn:
                if (TCUserMgr.getInstance().hasUser()) {
                    startActivity(new Intent(mContext, VideoLoginActivity.class));
                    return;
                }
                WebViewActivity.actionStart(mContext,this.currentTcLiveInfo.link);
                break;
        }
    }

}
